<script setup>
import { nextTick, reactive, ref } from "vue";
import Selector from "@/components/difficultySelector.vue";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { QuillEditor } from "@vueup/vue-quill";
import CodeEditor from "@/components/CodeEditor.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addQuestionApi,
  editQuestionApi,
  getQuestionApi,
} from "@/api/question";

const mainFuncRef = ref();
const defaultCodeRef = ref();
const emit = defineEmits();
const isSubmitSuccess = ref(false);
const visible = ref(false);
const questionForm = reactive({
  questionId: "",
  title: "",
  difficulty: "",
  timeLimit: "",
  questionCase: "",
  spaceLimit: "",
  content: "",
  defaultCode: "",
  mainFunc: "",
});
const formRef = ref(null);

// 打开抽屉
async function open(questionId) {
  visible.value = true;
  await nextTick();

  if (questionId) {
    // 获取题目数据
    try {
      const resp = await getQuestionApi(questionId);
      Object.assign(questionForm, resp.data);
      defaultCodeRef.value.setAceCode(questionForm.defaultCode);
      mainFuncRef.value.setAceCode(questionForm.mainFunc);
    } catch (e) {
      ElMessage.error(e.message);
    }
  }
}

defineExpose({
  open,
});

// 表单校验规则
const rules = ref({
  title: [
    { required: true, message: "题目标题不能为空", trigged: "blur" },
    { min: 1, max: 50, message: "标题长度在1-50" },
  ],
  timeLimit: [
    { required: true, message: "时间限制不能为空", trigged: "blur" },
    { pattern: /^[0-9]*$/, message: "时间限制只能是数字", trigged: "blur" },
  ],
  difficulty: [
    { required: true, message: "难度不能为空", trigger: ["change"] },
  ],
  spaceLimit: [
    { required: true, message: "空间限制不能为空", trigged: "blur" },

    { pattern: /^[0-9]*$/, message: "空间限制只能是数字", trigged: "blur" },
  ],
  questionCase: [
    { required: true, message: "题目用例不能为空", trigged: "blur" },
    { min: 1, max: 1000, message: "请保持用例长度在1000" },
  ],
});

// 处理添加 / 编辑
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning("请填写正确的信息");
      return;
    }
    if (questionForm.defaultCode.length > 1000) {
      ElMessage.warning("默认代码块内容太长");
      return;
    }
    if (questionForm.mainFunc.length > 1000) {
      ElMessage.warning("main方法内容太长");
      return;
    }
    try {
      if (questionForm.questionId) {
        await editQuestionApi(questionForm);
        ElMessage.success("修改成功");
        visible.value = false;
        emit("edit");
      } else {
        await addQuestionApi(questionForm);
        ElMessage.success("添加成功");
        visible.value = false;
        emit("add");
      }
    } catch (e) {
      ElMessage.warning(e.message);
    }
  });
};

// 默认代码块
const handleEditorContent = (content) => {
  questionForm.defaultCode = content;
};
// main函数
const handleEditorMainFun = (content) => {
  questionForm.mainFunc = content;
};

const handleClose = () => {
  if (isSubmitSuccess.value) {
    isSubmitSuccess.value = false;

    clearForm();
  } else {
    ElMessageBox.confirm("是否关闭弹窗? 未保存的内容将会丢失", "Warning", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        visible.value = false;
        await nextTick();
        clearForm();
      })
      .catch(() => {
        visible.value = true;
      });
  }
};

const clearForm = () => {
  for (const key in questionForm) {
    if (questionForm.hasOwnProperty(key)) {
      questionForm[key] = "";
    }
  }
};
</script>
    
<template>
  <el-drawer
    v-model="visible"
    size="50%"
    :with-header="false"
    :destroy-on-close="true"
    :before-close="handleClose"
  >
    <el-form ref="formRef" :model="questionForm" size="default" :rules="rules">
      <el-form-item prop="title">
        <el-input
          show-word-limit
          maxlength="50"
          v-model="questionForm.title"
          placeholder="请输入标题"
        ></el-input>
      </el-form-item>
      <el-form-item prop="difficulty">
        <Selector
          placeholder="请选择题目难度"
          v-model="questionForm.difficulty"
        ></Selector>
      </el-form-item>
      <el-form-item prop="timeLimit">
        <el-input
          maxlength="20"
          v-model="questionForm.timeLimit"
          placeholder="请输入时间限制(单位:ms)"
        ></el-input>
      </el-form-item>
      <el-form-item prop="spaceLimit">
        <el-input
          maxlength="20"
          v-model="questionForm.spaceLimit"
          placeholder="请输入空间限制(单位:字节)"
        ></el-input>
      </el-form-item>
      <el-form-item prop="content">
        <div class="editor">
          <quill-editor
            placeholder="请输入题目内容"
            v-model:content="questionForm.content"
            content-type="html"
          ></quill-editor>
        </div>
      </el-form-item>
      <el-form-item prop="questionCase">
        <el-input
          show-word-limit
          maxlength="1000"
          v-model="questionForm.questionCase"
          placeholder="请输入题目用例"
        ></el-input>
      </el-form-item>
      <el-form-item label="默认代码块:">
        <code-editor
          @update:value="handleEditorContent"
          ref="defaultCodeRef"
        ></code-editor>
      </el-form-item>
      <el-form-item label="main函数:">
        <code-editor
          @update:value="handleEditorMainFun"
          ref="mainFuncRef"
        ></code-editor>
      </el-form-item>
      <el-form-item>
        <el-button
          class="question-button"
          type="primary"
          plain
          @click="handleSubmit"
          >发布</el-button
        >
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
    
<style scoped lang="less">
.editor {
  width: 100%;
}
.question-button {
  width: 200px;
}

.el-form-item {
  flex-direction: column;
  :deep(.el-form-item__label) {
    justify-content: flex-start !important;
    font-weight: bold;
  }
}
</style>